<template>
  <div class="mtype-container">
    <div>为确保审核成功，请认真填写申请资料</div>
    <div class="mtype-form">
      <van-cell-group title="身份信息">
        <van-field
          ref="realname"
          v-model="formData.realname"
          required
          clearable
          label="姓名"
          placeholder="请输入真实姓名"
          :error-message="errorMsg.realname"
        />
        <van-field
          ref="idcardno"
          v-model="formData.idcardno"
          required
          clearable
          label="身份证号"
          placeholder="请输入身份证号"
          :error-message="errorMsg.idcardno"
        />
      </van-cell-group>
      <van-cell-group title="工作信息">
        <van-field
          ref="occupation"
          v-model="formData.occupation"
          required
          readonly
          @click="showPopupOccupation"
          label="职业"
          is-link
          arrow-direction="down"
          placeholder="请选择职业"
          :error-message="errorMsg.occupation"
        />
        <van-field
          ref="organization"
          v-model="formData.organization"
          required
          clearable
          label="现工作单位/就读学校"
          placeholder="请输入现工作单位或就读学校"
          :error-message="errorMsg.organization"
        />
        <van-field
          ref="qualification"
          v-model="formData.qualification"
          required
          readonly
          is-link
          arrow-direction="down"
          @click="showPopupQualification"
          label="学历"
          placeholder="请选择学历"
          :error-message="errorMsg.qualification"
        />
        <van-field
          ref="income"
          v-model="formData.income"
          required
          clearable
          type="number"
          label="个人月收入"
          placeholder="请输入个人月收入"
          :error-message="errorMsg.income"
        />
      </van-cell-group>
      <van-cell-group title="地址信息">
        <van-field
          ref="addressText"
          v-model="addressText"
          @click="showPopupArea"
          required
          readonly
          is-link
          arrow-direction="down"
          label="地区"
          placeholder="请选择省/市/区"
          :error-message="errorMsg.addressText"
        />
        <van-field
          ref="addressDetail"
          v-model="formData.addressDetail"
          required
          clearable
          label="详细地址"
          placeholder="精确到门牌号"
          :error-message="errorMsg.addressDetail"
        />
        <van-field v-model="formData.postalCode" clearable label="邮编" placeholder="请输入邮政编码" />
      </van-cell-group>
      <van-cell-group title="联系信息">
        <van-field
          ref="mobile"
          v-model="formData.mobile"
          required
          clearable
          label="手机号"
          placeholder="请输入手机号"
          :error-message="errorMsg.mobile"
        />
        <van-field
          ref="code"
          v-model="formData.code"
          center
          required
          clearable
          label="短信验证码"
          placeholder="请输入验证码"
          :error-message="errorMsg.code"
        >
          <van-button
            slot="button"
            size="small"
            :disabled="countdown > 0"
            @click="sendMobileCode"
            type="primary"
          >{{ countdown ? countdown + 's' : '发送验证码'}}</van-button>
        </van-field>
      </van-cell-group>
    </div>
    <div class="mtype-action">
      <van-button size="large" block @click="onSubmit" :disabled="disableSubmit">提交</van-button>
    </div>
    <!-- 地址选择 -->
    <van-popup v-model="showArea" position="bottom">
      <van-area
        :area-list="areaList"
        @confirm="onAddressConfirm"
        @cancel="closePopupArea"
        :value="apply.areaCode"
      />
    </van-popup>
    <!-- 职业选择 -->
    <van-popup v-model="showOccupation" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="职业"
        :columns="options.occupations"
        @cancel="closePopupOccupation"
        @confirm="onOccupationConfirm"
      />
    </van-popup>
    <!-- 学历选择 -->
    <van-popup v-model="showQualification" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="学历"
        :columns="options.qualifications"
        @cancel="closePopupQualification"
        @confirm="onQualificationConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import dist from '../../common/dist'
import validator from '../../common/validator'
import {
  Row,
  Col,
  Cell,
  Button,
  CellGroup,
  Field,
  Area,
  Icon,
  Image,
  Popup,
  Picker,
  Lazyload
} from 'vant'

export default {
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Area.name]: Area,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Image.name]: Image,
    [Picker.name]: Picker,
    Lazyload
  },

  data () {
    this.areaList = dist
    return {
      sms: '',
      countdown: 0,
      apply: {
        memberId: 0,
        typeId: 0,
        realname: '',
        idcardno: '',
        mobile: '',
        province: '',
        city: '',
        district: '',
        areaCode: '',
        postalCode: '',
        addressDetail: '',
        occupation: '',
        qualification: '',
        organization: '',
        income: '',
        code: ''
      },
      showArea: false,
      showOccupation: false,
      showQualification: false,
      disableSubmit: false,
      options: {
        occupations: [
          '事业单位/企业负责人',
          '科学研究人员',
          '工程技术（计算机）人员',
          '农业技术人员',
          '飞行和船舶技术等人员',
          '卫生专业技术人员',
          '经济业务人员',
          '金融业务人员（不含会计师）',
          '法律专业人员',
          '教学人员',
          '文学艺术工作人员',
          '体育工作人员',
          '新闻出版、文化工作人员',
          '其他专业技术人员',
          '会计师',
          '行政办公人员',
          '安全保卫和消防工作人员',
          '邮政和电信业务人员',
          '其他办事人员和有关人员',
          '商业、服务业人员',
          '农、林、牧、渔、水利业生成人员',
          '生成、运输设备操作人员及有关人员',
          '军人',
          '学生',
          '外交人员',
          '不便分类的其他从业人员',
          '无职业活动人员',
          '退休人员',
          '家庭主妇'
        ],
        qualifications: [
          '小学',
          '初级中学',
          '高级中学、中专、职校、中技',
          '专科（高职、高专、高技）',
          '本科',
          '硕士研究生',
          '博士研究生',
          '其他'
        ]
      },
      errorMsg: {
        realname: '',
        idcardno: '',
        mobile: '',
        postalCode: '',
        occupation: '',
        qualification: '',
        organization: '',
        income: '',
        addressText: '',
        addressDetail: '',
        code: ''
      },
      rules: {
        realname: [{ required: true, message: '请输入真实姓名' }],
        idcardno: [
          {
            validator: (rule, value, callBack) => {
              let reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/
              if (!value) {
                callBack('请输入身份证号')
              } else if (reg.test(value)) {
                callBack()
              } else {
                callBack('请输入正确的身份证号')
              }
            }
          }
        ],
        mobile: [
          {
            validator: (rule, value, callBack) => {
              if (!value) {
                callBack('请输入手机号码')
              } else if (/^[1][3-9][0-9]{9}$/.test(value)) {
                callBack()
              } else {
                callBack('请输入正确的手机号码')
              }
            }
          }
        ],
        addressText: [{ required: true, message: '请选择地区' }],
        organization: [{ required: true, message: '请输入就业单位或就读学校' }],
        qualification: [{ required: true, message: '请选择学历' }],
        occupation: [{ required: true, message: '请选择职业' }],
        addressDetail: [{ required: true, message: '请输入详细地址' }],
        income: [{ required: true, message: '请选择收入范围' }],
        code: [{ required: true, message: '请输入验证码' }]
      }
    }
  },

  created () {
    this.apply.typeId = this.$route.params.id
    this.onLoad()
    // this.validator = validator(this.rules, this.apply)
  },
  watch: {
    formData: {
      handler (cv, ov) {
        cv['addressText'] = this.addressText
        this.validator = validator(this.rules, cv)
      },
      deep: true
    }
  },
  computed: {
    formData () {
      return this.apply
    },
    addressText () {
      var { province, city, district, areaCode } = this.apply
      if (areaCode) {
        var arr = [province, city, district]
        if (province && province === city) {
          arr.splice(1, 1)
        }
        return arr
          .filter(function (text) {
            return text
          })
          .join('/')
      }
      return ''
    }
  },

  methods: {
    onAddressConfirm (node) {
      this.apply.province = node[0].name
      this.apply.city = node[1].name
      this.apply.district = node[2].name
      this.apply.areaCode = node[2].code
      this.showArea = false
    },
    onOccupationConfirm (node) {
      console.log(node)
      this.apply.occupation = node
      this.showOccupation = false
    },
    onQualificationConfirm (node) {
      console.log(node)
      this.apply.qualification = node
      this.showQualification = false
    },
    showPopupArea () {
      this.showArea = true
    },
    closePopupArea () {
      this.showArea = false
    },
    showPopupOccupation () {
      this.showOccupation = true
    },
    closePopupOccupation () {
      this.showOccupation = false
    },
    showPopupQualification () {
      this.showQualification = true
    },
    closePopupQualification () {
      this.showQualification = false
    },
    onChangeArea (e, v) {
      console.log(v)
    },
    onLoad () {
      this.axios
        .get('/member/apply')
        .then(response => {
          if (response.data) {
            this.apply = Object.assign({}, this.apply, response.data.fullData)
            console.log(this.apply)
            console.log(this.addressText)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    onSubmit () {
      console.log(this.formData)
      this.validate((errors, fields) => {
        if (errors) {
          if (fields.length > 0) {
            let first = fields.shift()
            console.log(first)
            this.$refs[first.field].focus()
          }
          console.log(this.errorMsg)
        } else {
          this.submit()
        }
        console.log(fields)
      })
    },
    submit () {
      this.disableSubmit = true
      this.axios
        .post('/member/apply/create', this.apply)
        .then(response => {
          if (response.data) {
            this.$router.replace({ name: 'member' })
          } else {
            this.$toast('提交失败~')
            this.disableSubmit = false
          }
        })
        .catch(error => {
          this.disableSubmit = false
          this.$toast(error)
        })
    },
    sendsms () {
      this.axios
        .post('/sms/captcha', {
          mobile: this.apply.mobile,
          scope: 'member'
        })
        .then(response => {
          if (response.data) {
            this.$toast('发送成功')
            this.countdown = 60
            this.countdownSubtract()
          } else {
            this.$toast('发送失败')
          }
        })
        .catch(error => {
          this.$toast(error)
        })
    },
    sendMobileCode () {
      this.validate(errors => {
        if (!errors) {
          this.sendsms()
        }
      }, 'mobile')
    },
    countdownSubtract () {
      if (this.countdown > 0) {
        setTimeout(() => {
          this.countdown -= 1
          this.countdownSubtract()
        }, 1000)
      }
    },
    /**
     * 清除验证提示
     * @param attrs
     */
    resetField (attrs) {
      attrs = !attrs
        ? Object.keys(this.errorMsg)
        : Array.isArray(attrs)
          ? attrs
          : [attrs]
      attrs.forEach(attr => {
        this.errorMsg[attr] = ''
      })
    },
    /**
     * 验证方法
     * @param callback
     * @param data
     */
    validate (callback, data) {
      this.validator.validate((errors, fields) => {
        this.resetField()
        if (errors) {
          fields.forEach(item => {
            this.errorMsg[item.field] = item.message
          })
        }
        callback && callback(errors, fields)
      }, data)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.mtype-container {
  position: relative;
  overflow: hidden;
  width: 100%;
  min-height: 100%;
}

.van-cell-group {
  margin-bottom: 10px;
}
.mtype-action {
  padding: 15px;
  width: 100%;

  .van-button--default {
    background-color: #e3c184;
    border-color: #e3c184;
    color: #805916;
    border-radius: 5px;
  }
}

.mtype-notice {
  padding: 20px 15px;
  .van-cell {
    border-radius: 30px;
    background: #fcfaed;
    padding: 5px 10px;
    font-size: 12px;
    line-height: 24px;
    &__left-icon {
      color: #ff5544;
    }
    &__right-icon {
      color: #f1b249;
    }
    &__title {
      color: #6d511f;
    }
    &__value {
      color: #f1b249;
    }
  }
}
.mtype-privilege {
  h1 {
    text-align: center;
    font-weight: 600;
    font-size: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #7d5609;
    small {
      font-weight: normal;
      opacity: 0.9;
    }
    &::before,
    &::after {
      content: "";
      width: 3px;
      height: 10px;
      background: #dfc087;
      margin: 0 10px;
      border-radius: 3px;
      transform: rotate(30deg);
    }
  }
  &-list {
    flex-wrap: wrap;
    padding: 5px;
    .van-col {
      padding: 10px 5px;
      text-align: center;
      font-weight: 300;
    }
  }
}
</style>
